//-------
// 窗口方法
//----
jQuery.extend({
	//消息框，自动隐藏
    // $.toast(iconNum, content,time,callback)
    //	iconNum = 0=感叹,1=成功,2=错误,3=疑问,4=锁，5=笑，6=笑
	toast: function (iconNum, content,time,callback) {
		var  p = new Promise(function (resolve, reject) {
	        layer.msg(content, {
				icon: iconNum,
				time: time || 1500,
				offset: '25%'
			}, function(index) {
				if(callback) {
					callback(index);
				}
				resolve(true)
			});
        });
		return p;
	},
	//模拟确认提示框
	//$.alert(iconNum, content, yesFn, title)
    //	iconNum = 0=感叹,1=成功,2=错误,3=疑问,4=锁，5=笑，6=笑
	alert:function(iconNum, content, yesFn, title){
		var  p = new Promise(function (resolve, reject) {
	        layer.confirm(content, {
	            icon: iconNum,
	            title: title || "提示框",
	            offset: '25%',
	            btn: ["确定"]
	        }, function(index, layero) {
	            if(yesFn) {
	                yesFn(index, layero);
	            } else {
	                layer.close(index);
	            }
	            resolve(true);
	        });
        });
		return p;
	},
	//模拟对话框,可确认，可取消
	//$.confirm(1,fn,fn)
    //	iconNum = 0=感叹,1=成功,2=错误,3=疑问,4=锁，5=笑，6=笑
	confirm: function(content, yesFn, cancelFn) {
		var  p = new Promise(function (resolve, reject) {
		    layer.confirm(content, {
	            icon: 3,
	            title: '提示框',
	            offset: '25%'
	        }, function(index, layero) {
	            if(yesFn) {
	                yesFn(index, layero);
	            } else {
	                layer.close(index);
	            }
	            resolve(true);
	        }, function(index) {
	            if(cancelFn){
	                cancelFn(index);
	            } 
	            reject(false);
	            layer.close(index);
	        });
        });
		return p;
    },
    //获取路径
    getUrl:function(sPath){
        var url = '';
        var appPath = window.__webConfig__.web_entrance.replace('//index.php','/index.php');
        if($.isPlainObject(sPath)){
            var surl =( sPath.url || '');
            delete sPath.url;
            if( 
                window.location.href.indexOf('/admin/views') !=-1 
                && surl.indexOf('/admin/views') == -1 
                && surl.indexOf('http') == -1 
            ){
                surl = '/admin/views/' + surl;
            }
            url =  appPath+"/"+ surl +"?"+$.param(sPath,true);
        }else{
            if(
                window.location.href.indexOf('/admin/views') !=-1 
                && sPath.indexOf('/admin/views') == -1
                && sPath.indexOf('/admin/soft') == -1
                && sPath.indexOf('http') == -1
            ){
                sPath = '/admin/views/' + sPath;
            }
            url = appPath+"/"+ sPath;
        }
        if( String(sPath || '').indexOf('http') != -1 ){
            return sPath;
        }else{
            return encodeURI( url ) + "&_rnd_=" + Math.random();
        }
    },
    //全屏窗口
    openFullWin: function(sPath, sName) {
        var _iX = window.screen.availWidth - 10,
            _iY = window.screen.availHeight - 50,
            _sName = sName || "";
        try {
            var page =  window.open(this.getUrl(sPath), _sName, "left=0,top=0,width=" + _iX + ",height=" + _iY + ",location=no,status=no,menubar=no,scrollbars=yes,resizable=yes");
            page.onload=function(){ page.document.title=sName || document.title; };
            return page;
        } catch(e) {
           //$.toast(2, "打开窗口失败：" + e);
        }
    },
    //定义大小窗口
    //$.openWin(sPath, sName, area)
    openWin: function(sPath, sName, area) {
        var _width = parseInt( area ? area[0] : area ) || 800,
            _height = parseInt( area ? area[1] : area) || 550,
            _sName = sName || "",
            _iL = (window.screen.availWidth - 10 - _width) / 2,
            _iT = (window.screen.availHeight - 30 - _height) / 2;
        if(_iL < 0) _iL = 0;
        if(_iT < 0) _iT = 0;
        try {
            var page= window.open(this.getUrl(sPath), _sName, "left=" + _iL + ",top=" + _iT + ",width=" + _width + ",height=" + _height + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,center=yes");
            page.onload=function(){ page.document.title=sName || document.title; };
            return page;
        } catch(e) {
            //$.toast(2, "打开窗口失败：" + e);
        }
    },
    //Iframe窗口 
    //$.openIframe(url,title,area,btn,opt)
    openIframe:function(url,title,area,btn,yesFn,opt){
        var area = area || ['800px', '550px'];
        var maxheight = $("body").height() - 25;
        if( (parseInt(area[1]) || 0) > maxheight){ area[1]=maxheight+'px';  }
        var defaults = {
            type: 2,
            title: title,
            content:  this.getUrl(url) ,
            offset: opt && opt.offset || 'auto',
            anim: -1,
            isOutAnim: false,
            area: area,
            maxmin: (opt && opt.isMaxmin) || true,
            fixed: false,
            moveOut: true,
            resize: true,
            //shade:0.1,
            btnAlign: (opt && opt.btnAlign) || 'r',
            btn:btn ||  null,
            success: function(layero, index) {
                
            },
            yes: function(index, layero) {
                if(yesFn) {
                    yesFn(index, layero);
                } else {
                    layer.close(index);
                }
            },
            cancel: function(index) { //右上角关闭按钮
                if(opt && opt.cancelFn) opt.cancelFn(index);
            },
            end: function() { //层销毁就触发
                if(opt && opt.endFn) opt.endFn();
            },
            full: function(layero) {//最大化触发
                if(opt && opt.fullFn) opt.fullFn();
            },
            min: function(layero) {//最小化触发
                if(opt && opt.minFn) opt.minFn();
            },
            restore: function(layero) {//还原触发
                if(opt && opt.restoreFn)  opt.restoreFn();
            }
        }
        return layer.open($.extend(true,{},defaults, opt));
    },
    //模态窗口
    //$.open(content, title,successFn, yesFn, area, opt)
    open:function(title,content,area,opt){
        if( $.isPlainObject(area) )   opt = area;
        return new Promise(function (resolve, reject) {
            $.openModalDialog(content,title,null,resolve,area,opt);
        });
    },
    //$.openModalDialog(content, title,successFn, yesFn, area, opt)
    openModalDialog: function(content, title,successFn, yesFn, area, opt) {
        var def_btn = ['确定', '取消'];
        if (opt && opt.btn) {  def_btn = opt.btn; }
        if (opt && opt.btn === null) { def_btn = null; }
        var defaults = {
            type: (opt && opt.type) || 1,
            skin: 'xw-layui-layer', //加上边框
            title: title,
            content: content,
            anim: -1,
            isOutAnim: false,
            area: area || ['800px', '550px'],
            maxmin: (opt && opt.isMaxmin) || true,
            fix: false,
            move:(opt && opt.move===false) ?  false  : '.layui-layer-title',
            moveOut: true,
            offset:(opt && opt.offset) || "auto",
            resize: true,
            btnAlign: (opt && opt.btnAlign) || 'r',
            btn: def_btn,
            success: function(layero, index) { //layero 当前层 dom, index 当前层索引
            	if(layui && layui.form && layui.form.render)
                   layui.form.render();
                if(successFn)  
                    successFn(index, layero);
            },
            yes: function(index, layero) {
                if(opt && opt.btn1)  opt.btn1(index);
                if(yesFn) {
                    yesFn(index, layero);
                } else {
                    layer.close(index);
                }
            },
            cancel: function(index) {//右上角关闭按钮
                if(opt && opt.cancelFn) opt.cancelFn(index);
            },
            btn2: function(index) {
                if(opt && opt.cancelFn)  opt.cancelFn(index);
            },
            end: function() { //层销毁就触发
                if(opt && opt.endFn)  opt.endFn();
            },
            full: function(layero) { //最大化触发
                if(opt && opt.fullFn)  opt.fullFn();
            },
            min: function(layero) {//最小化触发
                if(opt && opt.minFn) opt.minFn();
            },
            restore: function(layero) {//还原触发
                if(opt && opt.restoreFn) opt.restoreFn();
            }
        };
        return layer.open($.extend(true,{},defaults, opt));
    },
    //关闭窗口
    //$.close()
    close:function(){
    	window.close();
    	parent.layer.close(parent.layer.getFrameIndex(window.name));
    },
    //全屏
    //$.fullScreen()
    fullScreen :function () {
        var el = document.documentElement;
        var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen;
        if (typeof rfs != "undefined" && rfs) {
            rfs.call(el);
        };
        return;
    },
    //退出全屏
    //$.exitScreen()
    exitScreen:function () {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        }
        else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        if (typeof cfs != "undefined" && cfs) {
            cfs.call(el);
        }
    },
    //导入窗口
    openImportHandle:function(url,successFn,successFn2){
    	function yesFn(index){
    		if(!$("#open_file_id").val()){
    			$.toast(0,"请选择文件");
    			return;
    		}
    		var _loadingIdx = layer.load(1);
    		$.ajaxFileUpload({
                url: __webConfig__.web_entrance +url , 
                secureuri: false, //一般设置为false
                fileElementId: 'open_file_id', 
                dataType: 'json', //返回值类型 一般设置为json
                success: function (resp, status) {
                	if(status=="success"){
                		$.toast(1,"导入成功！");
                		if(successFn && typeof(successFn) !="string" ){ successFn(resp); }
                		if(successFn2){ successFn2(resp); }
                	}else{
                		$.alert(0, resp.msg);
                	}
                	layer.close(index);
                	layer.close(_loadingIdx);
                },
                error: function (data, status, e) {
                    $.alert(0,"请求失败:" + (data.responseText || e));
                    layer.close(index);
                    layer.close(_loadingIdx);
                }
            });
    	}
    	var $a = '';
    	if( typeof(successFn)== "string"){
    		$a = `<a href="${successFn}" download style="display: block;color: #1e9fff;text-align: left;">下载导入模板</a>`;
    	}
    	var html = `
    		<div style="padding: 15px 60px;line-height: 40px;" > ${$a}
    			<input type="file" id="open_file_id" name="file"  />
    		</div>
    	`;
    	$.openModalDialog(html, "导入",null,yesFn,["400px", "200px"]);
    }
});